/**
 * Copyright(c) 2025 hbswxx.com, All Rights Reserved. Author: kouqiang Create date: 2025/5/30
 */
package cn.sw.syncdata.threadpool;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * description:
 *
 * @author kouqiang
 * @date 2025/5/30 08:44
 */
public class ThreadPoolManager {
    // 核心线程数：CPU核心数 × 2（I/O密集型任务）
    private static final int CORE_POOL_SIZE = Runtime.getRuntime().availableProcessors() * 2;
    // 最大线程数：核心数的2倍
    private static final int MAX_POOL_SIZE = CORE_POOL_SIZE * 2;
    // 队列容量：根据峰值QPS计算（假设峰值1000，任务处理时间50ms）
    private static final int QUEUE_CAPACITY = 10;
    // 线程存活时间：600秒
    private static final long KEEP_ALIVE_TIME = 600L;

    // 自定义线程工厂
    private static final ThreadFactory threadFactory = new ThreadFactory() {
        private final AtomicInteger threadNumber = new AtomicInteger(1);
        @Override
        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r, "order-processing-thread-" + threadNumber.getAndIncrement());
            thread.setDaemon(false);
            thread.setPriority(Thread.NORM_PRIORITY);
            return thread;
        }
    };
//    // 自定义拒绝策略：记录日志并尝试放入另一个紧急队列
//    private static final RejectedExecutionHandler rejectedHandler = (runnable, executor) -> {
//        System.err.println("Order task rejected, thread pool is full: " + runnable);
//    };
    public static final ThreadPoolExecutor EXECUTOR = new ThreadPoolExecutor(
            CORE_POOL_SIZE,
            MAX_POOL_SIZE,
            KEEP_ALIVE_TIME,
            TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(QUEUE_CAPACITY),
            threadFactory
    );
    // 提交任务
    public static void submitThread(Runnable task) {
        EXECUTOR.execute(() -> {
            try {
                task.run();
            } catch (Exception e) {
                // 任务内异常捕获
                System.err.println("Order task exception: " + e.getMessage());
            }
        });
    }
    public static void shutdown() {
        EXECUTOR.shutdown();
        try {
            if (!EXECUTOR.awaitTermination(60, TimeUnit.SECONDS)) {
                EXECUTOR.shutdownNow();
            }
        } catch (InterruptedException e) {
            EXECUTOR.shutdownNow();
            Thread.currentThread().interrupt();
        }
    }
}
